package it.sebsibenal.client.pages;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

public class NuovoBranoDialog extends DialogBox {

	private TextBox tbAutore;
	private TextBox tbTitolo;
	private Button btnSalva;

	public NuovoBranoDialog() {
		setHTML("Nuovo brano");
		
		FlexTable grid = new FlexTable();
		setWidget(grid);
		grid.setSize("240px", "209px");
		
		Label lblAutore = new Label("Autore");
		grid.setWidget(0, 0, lblAutore);
		
		tbAutore = new TextBox();
		grid.setWidget(0, 1, tbAutore);
		
		Label lblTitolo = new Label("Titolo");
		grid.setWidget(1, 0, lblTitolo);
		
		tbTitolo = new TextBox();
		grid.setWidget(1, 1, tbTitolo);
		
		HorizontalPanel horizontalPanel = new HorizontalPanel();
		horizontalPanel.setSize("100%", "100%");
		horizontalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		grid.setWidget(2, 0, horizontalPanel);
		
		btnSalva = new Button("Salva");
		horizontalPanel.add(btnSalva);
		
		Button btnAnnulla = new Button("Annulla");
		horizontalPanel.add(btnAnnulla);
		
		grid.getFlexCellFormatter().setColSpan(2, 0, 2);
		
		btnAnnulla.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				hide();
			}
		});
	}

	@Override
	public void show() {
		super.show();
		center();
		tbAutore.setFocus(true);
	}

	public void addSaveHandler(SaveHandler handler) {
		btnSalva.addClickHandler(handler);
		handler.setSaveCallback(new AsyncCallback<Void>() {
			@Override
			public void onSuccess(Void result) {
				hide();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				hide();
			}
		});
	}
	
	public static abstract class SaveHandler implements ClickHandler {
		AsyncCallback<Void> saveCallback;
		
		public void setSaveCallback(AsyncCallback<Void> saveCallback) {
			this.saveCallback = saveCallback;
		}
		public void confirmSave() {
			saveCallback.onSuccess(null);
		}
		public void errorOnSave(Throwable e) {
			saveCallback.onFailure(e);
		}
	}

	public String getAutore() {
		return tbAutore.getText();
	}

	public String getTitolo() {
		return tbTitolo.getText();
	}
	
	
}
